package com.runa.monitor.platinterface.meter3_0.session;

import com.runa.monitor.platinterface.meter3_0.task.TaskManager;
import com.runa.monitor.platinterface.meter3_0.task.TaskProxy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author diandian
 * @Date 2022/11/20 15:33
 */
@Component
public class SessionManager {
    @Resource
    private TaskManager taskQueue;

    private SessionManager(){
    }

    public void notifySendMsg(String identity, String msg) {
        SessionProxy sessionProxy = WebSocketPool.getSession(identity);
        if (sessionProxy == null) {
            return;
        }
        sessionProxy.setSendMsg(msg);
        sessionProxy.setSessionState(SessionProxy.SessionState.send);
    }

    public void notifyReceiveMsg(String identity, String msg) {
        SessionProxy sessionProxy = WebSocketPool.getSession(identity);
        if (sessionProxy == null) {
            return;
        }
        SessionProxy.SessionState sessionState = sessionProxy.getSessionState();
        //一问一答
        if (!SessionProxy.SessionState.send.equals(sessionState)) {
            return;
        }
        sessionProxy.setReceiveMsg(msg);
        sessionProxy.setSessionState(SessionProxy.SessionState.receive);
    }

    public void notifyEndHandleMsg(String identity) {
        SessionProxy sessionProxy = WebSocketPool.getSession(identity);
        if (sessionProxy == null) {
            return;
        }
        //处理完数据后，标记当前会话为空闲期，清楚缓存数据
        sessionProxy.setSessionState(SessionProxy.SessionState.free);
        sessionProxy.setSendMsg(null);
        sessionProxy.setReceiveMsg(null);
        Map<String, Object> userProperties = sessionProxy.getSession().getUserProperties();
        userProperties.clear();
        //同时通知其他人，session会话目前解放，可以进行其他操作
        TaskProxy taskProxy = sessionProxy.getTaskProxy();
        taskQueue.removeCurrent(taskProxy,identity);

    }
}